package com.jfy.cmai.robot.http;



import com.jfy.cmai.robot.utils.SPKeys;
import com.jfy.cmai.robot.utils.SPUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class HeaderInterceptor implements Interceptor {

    @Override
    public Response intercept(@NotNull Interceptor.Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        String token = SPUtil.read(SPKeys.APPINFO, SPKeys.TOKEN, "");
        builder.addHeader("Accept", "application/json");
        builder.addHeader("Authorization", token);
        //获取用户所使用的请求方式
        String method = request.method();
        if("GET".equals(method)){
            //原始的请求接口
            HttpUrl httpUrl = request.url();
            Map<String, String> params = new TreeMap<>();
            Set<String> parameterNames = httpUrl.queryParameterNames();
            if(!parameterNames.isEmpty()){
                for(String s : parameterNames){
                    params.put(s, httpUrl.queryParameter(s));
                }
                String url = httpUrl.toString();
                return chain.proceed(builder.url(url).build());
            }else{
                return chain.proceed(builder.build());
            }
        }else{
            if(request.body() instanceof FormBody){
                FormBody formBody = (FormBody) request.body();
                if (formBody.size() != 0){
                    FormBody.Builder formBodyBuilder = new FormBody.Builder();
                    Map<String,String> params = new TreeMap<>();
                    for (int i = 0; i < formBody.size(); i++) {
                        formBodyBuilder.addEncoded(formBody.encodedName(i),formBody.encodedValue(i));
                        params.put(formBody.encodedName(i),formBody.value(i));
                    }
                    builder.method(request.method(),formBodyBuilder.build());
                    return chain.proceed(builder.build());
                }
            }
        }
        return chain.proceed(builder.build());
    }
}
